export const showMessage = function (message, config = { icon: 'none' }) {
  return uni.showToast({
    title: message,
    icon: config.icon,
  })
}

export const wait = function(delay) {
  return new Promise(r => setTimeout(r, delay))
}

// 停止冒泡行为
export function stopBubble(e) {
  // 如果提供了事件对象，则这是一个非IE浏览器
  if (e && e.stopPropagation)
    // 因此它支持W3C的stopPropagation()方法
    e.stopPropagation()
  // 否则，我们需要使用IE的方式来取消事件冒泡
  else window.event.cancelBubble = true
}

// 阻止浏览器的默认行为
export function stopDefault(e) {
  // 阻止默认浏览器动作(W3C)
  if (e && e.preventDefault) e.preventDefault()
  // IE中阻止函数器默认动作的方式
  else window.event.returnValue = false
  return false
}

// 截断字符串
export const truncateString = (string, length) => {
  return string.length < length ? string : `${string.slice(0, length - 3)}...`
}
// truncateString('Hi, I should be truncated because I am too loooong!', 36)   // 'Hi, I should be truncated because...'

// 去除字符串中的HTML
export const stripHtml = html => {
  return new DOMParser().parseFromString(html, 'text/html').body.textContent || ''
}

// 获取一个变量的类型
export const getTypeof = obj => {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}


export function cloneUtil(target) {
	// [object Array]  [object Object]  [object Function]
	const type = Object.prototype.toString.call(target)
	let res
	if (type.includes('Array')) {
		res = []
	} else if (type.includes('Object')) {
		res = {}
	} else {
		return ''
	}
  
	for (let i in target) {
		if (typeof target[i] === 'object') {
			res[i] = cloneUtil(target[i])
		} else {
			res[i] = target[i]
		}
	}

	return res
}

// 防抖
export const debounce = function(fn, delay = 500) {
  let timer = null;

  return (...args) => {
    if(timer) clearTimeout(timer);

    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  }
}